package com.leetcode.双周赛.第49场;

import java.util.Arrays;

/**
 * @author: xiaomi
 * @date: 2021/4/3
 * @description: 5708. 统计一个数组中好对子的数目
 * https://leetcode-cn.com/contest/biweekly-contest-49/problems/count-nice-pairs-in-an-array/
 */
public class B_5708_统计一个数组中好对子的数目 {
    static B_5708_统计一个数组中好对子的数目 action = new B_5708_统计一个数组中好对子的数目();

    public static void main(String[] args) {

        //System.out.println(action.getRev(12));
//        test1();
//        test2();
    }

    static void test1() {
        //
        int[] nums = new int[]{42, 11, 1, 97};
        int res = action.countNicePairs(nums);

        System.out.println("res = " + res);
    }

    static void test2() {
        //
        int[] nums = new int[]{8047408, 192867140, 497837845, 279787822, 151999002, 168514912, 193424242, 399636844, 132424231, 476736524, 267958611, 493350382, 476382727, 232939232, 197000791, 295291645, 126313621, 374645524, 7956597, 1376731, 496463745, 234481430, 359130803, 287625836, 250572050, 42311324, 477434624, 493231448, 493231244, 150494051, 184645534, 365252413, 495764582, 335976531, 384564332, 377151623, 198736741, 335161533, 245552540, 194897341, 83911938, 220562020, 496645745, 287151782, 374635526, 372483324, 485101584, 271797172, 244949442, 254333303, 251635002, 459181805, 472392123, 241350140, 256121502, 336895621, 354635302, 358909704, 194525491, 3606063, 194150341, 63477436, 341936141, 60299206, 69811896, 369928813, 229926920, 435310522, 299542980, 463777364, 164534512, 305885501, 437181734, 74288247, 487281835, 171161022, 423966312, 496989544, 452633252, 252433101, 141565141, 315895501, 478897927, 232532230, 472451262, 160504114, 476666674, 6179716, 251483002, 474777474, 443532332, 475808424, 457514604, 400936002, 384878483, 172616122, 283292232, 165645615, 392000144, 378636873};
        int res = action.countNicePairs(nums);
        System.out.println("res = " + res);
    }


    /**
     * 失误了没有考虑int  越界的情况
     *
     * @param nums
     * @return
     */
    public int countNicePairs(int[] nums) {
        int len = nums.length;
        int[] arr = new int[len];
        for (int i = 0; i < len; i++) {
            int temp = getRev(nums[i]);
            arr[i] = nums[i] - temp;
        }
        Arrays.sort(arr);
        int begin = 0, end = 1;
        long sum = 0;
        while (end < len) {
            if (arr[end] == arr[end - 1]) {
                end++;
            } else {
                long size = end - begin;
                sum += ((size * (size - 1)) >> 1);
                begin = end;
                end++;
            }
        }
        if (begin != end) {
            long size = end - begin;
            sum += ((size * (size - 1)) >> 1);
        }
        return (int) (sum % (1000_000_000 + 7));
    }

    private int getRev(int num) {
        int res = 0;
        while (num != 0) {
            int i = num % 10;
            res = res * 10 + i;
            num = num / 10;
        }
        return res;
    }


}
